package multicast

import (
	"fmt"
	"net"
	"strings"
)

type Handler interface {
	Run(listenner *net.UDPConn, ifi net.Interface)
}

func Listen(mip string, port int, handler Handler) {
	ifs, _ := net.Interfaces()
	pMaddr, addrErr := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", mip, port))
	if addrErr == nil {
		for _, inter := range ifs {
			addrs, _ := inter.Addrs()
			isLocal := false
			for _, addr := range addrs {
				saddr := addr.String()
				if strings.Contains(saddr, "127.0.0.1") {
					isLocal = true
					break
				}
			}
			if isLocal {
				continue
			}
			pListenner, _ := net.ListenMulticastUDP("udp", &inter, pMaddr)
			if pListenner != nil && handler != nil {
				fmt.Println("listen-----on---", inter.Name, mip, port)
				//pIf := &inter
				go handler.Run(pListenner, inter)
			}

		}
	} else {
		fmt.Println("error listen---------", addrErr)
	}

}
